package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.common.widgets.load.view.AbsView;
import com.xiaocz.common.widgets.recycler.RecyclerViewAdapter;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.adapter.FlowRecordListAdapter;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.AllFlowRecord;
import com.xiaocz.hblsubstitutedriving.model.FlowRecord;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2019/7/23
 * Created by xiaocz
 * Describe 我的账户
 */
public class MyAccountActivity extends BaseActivity {

    @BindView(R.id.tv_all_number)
    TextView tvAllNumber;
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    @BindView(R.id.tv_ye)
    TextView tvYe;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recycler_view)
    public RecyclerView mRecyclerView;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private FlowRecordListAdapter flowRecordListAdapter;

    public static void show(Context context) {
        Intent intent = new Intent(context, MyAccountActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_my_account;
    }

    @OnClick({R.id.btn_withdraw_deposit, R.id.tv_sm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_withdraw_deposit://去提现
                Intent intent = new Intent(mContext, WithdrawDepositActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.tv_sm://可提现-说明
                dialogHint();
                break;
        }
    }

    private void dialogHint() {
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        if (info != null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("提示");
            builder.setMessage("账户余额需留足" + flowRecord.getDeposit() + "元，超过部分可提现");
            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(refreshLayout, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                webMyOrder();
            }
        });
        setRefresh();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 2) {
            webMyOrder();
        }
    }

    private int page = 1;

    private void setRefresh() {
        // 下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
                webMyOrder();
            }
        });
        //加载更多
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore();
                page++;
                webMyOrder();
            }
        });
        webMyOrder();
    }

    @Override
    protected void initData() {
        super.initData();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        flowRecordListAdapter = new FlowRecordListAdapter(new RecyclerViewAdapter.AdapterListenerImpl<FlowRecord>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<FlowRecord> holder, FlowRecord data) {
                super.onItemClick(holder, data);
                if(data.getOrderNo()!=null){
                    OrderDetailsActivity.show(mContext, data.getOrderNo());
                }
            }
        });
        mRecyclerView.setAdapter(flowRecordListAdapter);
        webMyOrder();
    }

    private AllFlowRecord flowRecord;

    /**
     * 我的流水
     */
    private void webMyOrder() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("PageIndex", page);
        asyncHttpPostFormData.addFormData("PageSize", Common.Constant.pageSize);
        listCall.add(okHttpClient.post(Common.Constant.API_IP + "api/TiXian/QueryMoneyLog", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<AllFlowRecord>>() {
                }.getType();
                RspModel<AllFlowRecord> rspModel = getAnalysisBase(mLoadManager, response, type, "我的流水记录");
                if (rspModel == null) {
                    mLoadManager.showStateView(EmptyView.class);
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null) {
                            flowRecord = rspModel.getData();
                            tvAllNumber.setText(flowRecord.getTotalordercount());
                            tvAllMoney.setText(flowRecord.getTotalmoney());
                            tvBalance.setText(flowRecord.getBalance());
                            tvYe.setText(flowRecord.getTixianmoney());
                            if (!"[]".equals(flowRecord.toString())) {
                                if (page == 1) {
                                    flowRecordListAdapter.replace(flowRecord.getList());
                                } else {
                                    flowRecordListAdapter.add(flowRecord.getList());
                                }
                            } else {
                                mLoadManager.showStateView(EmptyView.class);
                            }
                        } else {
                            if (page == 1) {
                                mLoadManager.showStateView(EmptyView.class);
                            } else {
                                App.getInstance().showMessage(rspModel.getMessage());
                            }
                        }
                        break;
                    default:
                        mLoadManager.showStateView(ErrorView.class);
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        }));
    }
}
